package com.itobase.questionnaire.config;

import com.itobase.questionnaire.model.EnumList.States;
import com.itobase.questionnaire.model.Submission;
import com.itobase.questionnaire.model.Survey;
import com.itobase.questionnaire.repository.SubmitRepository;
import com.itobase.questionnaire.repository.SurveyRepository;
import com.itobase.questionnaire.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liucong
 * @date 2018/11/8
 */
@Component
public class ScheduledTasks {

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    MongoTemplate mongoTemplate;

    private static final int surveyInterval = 1000*60*60;
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Scheduled(fixedRate = surveyInterval)
    public void updateSurveyStats(){

        logger.warn("进行调查状态的更新");
        Date now = new Date();
        List<Survey> surveyList = surveyRepository.findAll();
        surveyList.forEach(survey -> {
            try {
                Date begin = DateUtil.parse_day(survey.getStartTime());
                Date end = DateUtil.parse_day(survey.getEndTime());
                if(now.compareTo(begin)>0 && now.compareTo(end)<0){
                    survey.setState(States.running);
                }else if(now.compareTo(begin)<0){
                    survey.setState(States.notStarted);
                }else if(now.compareTo(end)>0){
                    survey.setState(States.ended);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        logger.warn("更新结束");
    }

    @Scheduled(fixedRate = surveyInterval)
    public void deleteTestAccountSubmission(){
        final String congId = "5bd3cd96e18ae12864d155a4";
        final String yuId = "5bd3cd96e18ae12864d155ba";
        List<String> userIds = new ArrayList<>();
        userIds.add(congId);
        userIds.add(yuId);
        Criteria criteria = Criteria.where("userId").in(userIds);
        mongoTemplate.findAllAndRemove(Query.query(criteria), Submission.class);
        logger.info("已经定时删除刘聪、范煜的所有提交");
    }


}
